package cn.leonis.leetcode;

import java.util.Arrays;

/**
 * @Author Tobi
 * @Date 2021-07-14 下午10:24
 * 矩阵置零
 */
public class SetMatrixZeroesSolution {
    public static void main(String[] args) {
        int[][] matrix = new int[][]{{1, 1, 1}, {1, 0, 1}, {1, 1, 1}};
        SetMatrixZeroesSolution solution = new SetMatrixZeroesSolution();
        solution.setZeroes(matrix);
        for (int i = 0; i < matrix.length; i++) {
            System.out.println(Arrays.toString(matrix[i]));
        }
    }

    /**
     * 将存在0的行和列标记为true，再次遍历的时候，对应的行列为true的时候，就将其设置为0
     * @param matrix
     */
    public void setZeroes(int[][] matrix) {
        int m = matrix.length, n = matrix[0].length;
        boolean[] row = new boolean[m];
        boolean[] col = new boolean[n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (matrix[i][j] == 0) {
                    row[i] = col[j] = true;
                }
            }
        }

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (row[i] || col[j]) {
                    matrix[i][j] = 0;
                }
            }
        }
    }
}
